package com.qding.cupms.admin.rest.shiro;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.util.Assert;

import com.qding.cupms.common.utils.JsonUtil;

public class ShiroSessionRedisSerializer implements RedisSerializer<Object> {

    private final Converter<Object, byte[]> serializer;
    private final Converter<byte[], Object> deserializer;

    /**
     * Creates a new {@link JdkSerializationRedisSerializer} using the default class loader.
     */
    public ShiroSessionRedisSerializer() {
        this(new SerializingConverter(), new DeserializingConverter());
    }

    /**
     * Creates a new {@link JdkSerializationRedisSerializer} using a {@link ClassLoader}.
     *
     * @param classLoader
     * @since 1.7
     */
    public ShiroSessionRedisSerializer(ClassLoader classLoader) {
        this(new SerializingConverter(), new DeserializingConverter(classLoader));
    }

    /**
     * Creates a new {@link JdkSerializationRedisSerializer} using a {@link Converter converters} to serialize and
     * deserialize objects.
     * 
     * @param serializer
     *            must not be {@literal null}
     * @param deserializer
     *            must not be {@literal null}
     * @since 1.7
     */
    public ShiroSessionRedisSerializer(Converter<Object, byte[]> serializer, Converter<byte[], Object> deserializer) {

        Assert.notNull(serializer, "Serializer must not be null!");
        Assert.notNull(deserializer, "Deserializer must not be null!");

        this.serializer = serializer;
        this.deserializer = deserializer;
    }

    static boolean isEmpty(byte[] data) {
        return (data == null || data.length == 0);
    }

    public Object deserialize(byte[] bytes) {
        if (isEmpty(bytes)) {
            return null;
        }

        try {
            String jsonStr=new String(bytes);
            return JsonUtil.JsonStr2Java(jsonStr, Object.class);
//            return deserializer.convert(bytes);
        } catch (Exception ex) {
            throw new SerializationException("Cannot deserialize", ex);
        }
    }

    public byte[] serialize(Object object) {
        if (object == null) {
            return new byte[0];
        }
        try {
           String jsonStr= JsonUtil.Java2Json(object);
            return jsonStr.getBytes();
        } catch (Exception ex) {
            throw new SerializationException("Cannot serialize", ex);
        }
    }
}
